package com.bidevalution.dao.mapper;

import com.mongodb.client.result.DeleteResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * @author huyiqi
 * @date 2019/12/22
 */
@Repository(value = "mongoMapper")
public class MongoMapper {

    private static final String FILES_COLLECTION_NAME_FORMAT = "%s.files";
    private static final String CHUNKS_COLLECTION_NAME_FORMAT = "%s.chunks";
    private static final String DEFAULT_BUCKET_NAME = "fs";

    @Autowired(required = false)
    private MongoTemplate mongoTemplate;

    public boolean deleteFiles(String bucket, List<String> fileIds) {
        String fileCollectionName = getCollectionName(bucket, FILES_COLLECTION_NAME_FORMAT);
        String chunkCollectionName = getCollectionName(bucket, CHUNKS_COLLECTION_NAME_FORMAT);

        Query fileQuery = new Query(new Criteria().and("_id").in(fileIds));
        Query chunkQuery = new Query(new Criteria().and("files_id").in(fileIds));
        DeleteResult fileResult = mongoTemplate.remove(fileQuery, fileCollectionName);
        DeleteResult chunkResult = mongoTemplate.remove(chunkQuery, chunkCollectionName);

        return fileResult.wasAcknowledged() && chunkResult.wasAcknowledged();
    }


    public void dropCollections(String bucket) {
        String fileCollectionName = getCollectionName(bucket, FILES_COLLECTION_NAME_FORMAT);
        String chunkCollectionName = getCollectionName(bucket, CHUNKS_COLLECTION_NAME_FORMAT);

        mongoTemplate.getCollection(fileCollectionName).drop();
        mongoTemplate.getCollection(chunkCollectionName).drop();
    }

    private String getCollectionName(String bucket, String format) {
        if(StringUtils.isBlank(bucket)) {
            return String.format(format, DEFAULT_BUCKET_NAME);
        } else {
            return String.format(format, bucket);
        }
    }

    public List<Map> getMangoFilesInfo(String bucket) {
        String fileCollectionName = getCollectionName(bucket, FILES_COLLECTION_NAME_FORMAT);
        return mongoTemplate.findAll(Map.class, fileCollectionName);
    }
}
